

package com.oa.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oa.common.exception.RRException;
import com.oa.common.utils.AppUtils;
import com.oa.common.utils.Constant;
import com.oa.common.utils.PageUtils;
import com.oa.common.utils.Query;
import com.oa.modules.sys.dao.SysUserDao;
import com.oa.modules.sys.entity.SysUserEntity;
import com.oa.modules.sys.service.SysRoleService;
import com.oa.modules.sys.service.SysUserRoleService;
import com.oa.modules.sys.service.SysUserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 系统用户
 *
 * @author admin
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleService sysRoleService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SysUserEntity> page = new Query<SysUserEntity>().getPage(params);
        page.setPages(page.getCurrent() - 1);
        params = AppUtils.checkMap(params);
        return AppUtils.setPage(page, baseMapper.findPage(page, params), baseMapper.findRecords(page, params));

    }

    @Override
    public List<SysUserEntity> getOperator(String roleId) {
        return baseMapper.getOperator(roleId);

    }

    @Override
    public List<String> queryAllPerms(Long userId) {
        return baseMapper.queryAllPerms(userId);
    }

    @Override
    public List<Long> queryAllMenuId(Long userId) {
        return baseMapper.queryAllMenuId(userId);
    }

    @Override
    public SysUserEntity queryByUserName(String username) {

        // 正则表达式判断这个参数是否是手机号码如果返回false则不是手机号
        if (AppUtils.isPhone(username)) {
            return this.getOne(new QueryWrapper<SysUserEntity>().eq("mobile", username));
        } else {
            return baseMapper.queryByUserName(username);
        }
    }

    @Override
    @Transactional
    public void saveUser(SysUserEntity user) {
        user.setCreateTime(new Date());
        //sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        //user.setPassword(MD5Util.encrypt(user.getPassword()));
        user.setSalt(salt);
        this.save(user);

        //检查角色是否越权
        //checkRole(user);

        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    @Override
    @Transactional
    public void update(SysUserEntity user) {
        if (StringUtils.isBlank(user.getPassword())) {
            user.setPassword(null);
        }/*else{
			user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
		}*/
        this.updateById(user);

        //检查角色是否越权
        //checkRole(user);

        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    @Override
    public void deleteBatch(Long[] userId) {
        this.removeByIds(Arrays.asList(userId));
    }

    @Override
    public boolean updatePassword(Long userId, String password, String newPassword) {
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setPassword(newPassword);
        return this.update(userEntity,
                new QueryWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
    }

//    @Override
//    public List<Map<String, Object>> taskUserList(Map<String, Object> params) {
//        return baseMapper.auditUserList(params);
//    }

    @Override
    public PageUtils auditUserList(Map<String, Object> params) {
        params.put("status", Constant.YES_OR_NO.YES.getValue());
        IPage page = AppUtils.getPage(new Query<SysUserEntity>(), params);
        return AppUtils.setPage(page,baseMapper.auditUserListCount(params),baseMapper.auditUserList(page,params));
    }

    @Override
    public boolean validatorUserRole(SysUserEntity user) {
        List<Map<String, Object>> list = baseMapper.validatorUserRole(user);
        // 判断取出的list中的roleid如果包含管理员id就返回false(可以登录),如果返回true就是不可以登录
        for (Map<String, Object> map : list) {
            Integer index = 0;
            if (map != null) {
                index = Integer.valueOf(map.get("roleId").toString());
            }
            if (index != Constant.SUPER_ADMIN && index != Constant.ADMIN) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查角色是否越权
     */
    private void checkRole(SysUserEntity user) {
        if (user.getRoleIdList() == null || user.getRoleIdList().size() == 0) {
            return;
        }
        //如果不是超级管理员，则需要判断用户的角色是否自己创建
        if (user.getCreateUserId() == Constant.SUPER_ADMIN) {
            return;
        }

        //查询用户创建的角色列表
        List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());

        //判断是否越权
        if (!roleIdList.containsAll(user.getRoleIdList())) {
            throw new RRException("新增用户所选角色，不是本人创建");
        }
    }

    @Override
    public List<SysUserEntity> qryByOpenId(String openId) {
        return baseMapper.qryByOpenId(openId);
    }

}
